package cc.liyinghao.common.utils;


import lombok.Data;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class Ip2RegionService {
    private String ip;
    /**
     * 国家
     */
    private String country;
    /**
     * 区域
     */
    private String region;
    /**
     * 省份
     */
    private String province;
    /**
     * 城市
     */
    private String city;
    /**
     * 运营商
     */
    private String isp;

    public void getIp2Region(String ip) throws IOException {
        this.ip = ip;
        String dbPath = "src/main/resources/ip2region.xdb";
        String regex = "([^|]+)\\|([^|]+)\\|([^|]+)\\|([^|]+)\\|([^|]+)";
        Searcher searcher = null;

        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
            throw new IOException("failed to load ip2region db: " + e);
        }
        try {
            String searcherSearch = searcher.search(ip);
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(searcherSearch);
            if (matcher.matches()) {
                this.country = matcher.group(1);
                this.region = matcher.group(2);
                this.province = matcher.group(3);
                this.city = matcher.group(4);
                this.isp = matcher.group(5);
            } else {
                throw new IOException("解析ip失败");
            }
        } catch (Exception e) {
            throw new IOException("解析ip失败" + e);
        }

        // 3、关闭资源
        searcher.close();
    }
}


